package com.pinyoumei.app.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.adapter.MybillAdapter;
import com.pinyoumei.app.bean.MyBillBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.DateTimeUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2021-08-12.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-12        Administrator             新增Person类
 * 2021-08-12        Administrator             增加sex属性
 * 我的账单
 */
public class MyBillActivity extends BaseActivity implements View.OnClickListener {

    private List<MyBillBean.ResultBean.DealKindListBean> options1Items = new ArrayList<>();//一级菜单数据
    private TimePickerView datepickview;//日期选择器
    private OptionsPickerView pvOptions;//条件选择器
    private int source = 0;
    private int deal_kind = 0;
    private int page = 1;
    private String query_month = "";
    private TextView tv_time;
    private TextView text_type_name;
    private TextView tv_total_profit;
    private TextView tv_user_balance;
    private TextView tv_total_withdraw_amount;
    private MybillAdapter mybillAdapter;
    private RecyclerView rv1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_bill);
        source = getIntent().getIntExtra("source", 0);

        InitWidget();

        InitData(0);

    }

    private void InitWidget() {
        ImageView ivClose = findViewById(R.id.iv_close);
        ivClose.setOnClickListener(this);
        tv_time = findViewById(R.id.tv_time);
        text_type_name = findViewById(R.id.text_type_name);
        String time = String.valueOf(System.currentTimeMillis());//获取系统时间戳
        tv_time.setText(DateTimeUtils.stampToDatePoint(time));//设置当月时间
        tv_total_profit = findViewById(R.id.tv_total_profit);
        tv_user_balance = findViewById(R.id.tv_user_balance);
        tv_total_withdraw_amount = findViewById(R.id.tv_total_withdraw_amount);

        rv1 = findViewById(R.id.rv_1);
        rv1.setLayoutManager(new GridLayoutManager(this, 1, GridLayoutManager.VERTICAL, false));
        mybillAdapter = new MybillAdapter(R.layout.item_my_bill, null);
        mybillAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rv1.setAdapter(mybillAdapter);


        LinearLayout linear_type = findViewById(R.id.linear_type);
        linear_type.setOnClickListener(this);
        LinearLayout linear_time = findViewById(R.id.linear_time);
        linear_time.setOnClickListener(this);

        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        //正确设置方式 原因：注意事项有说明
        startDate.set(2000, 0, 1);
        //endDate.set(2100,11,31);
        //起始身份证日期选择
        datepickview = new TimePickerBuilder(MyBillActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//账单日时间选择的回调
                page = 1;
                String string = DateTimeUtils.stampToDatePoint(date.getTime()+"");//2019.03.15
                tv_time.setText(string);
                query_month = DateTimeUtils.stampToDate2(date.getTime()+"");
                InitData(0);
            }
        }).setLabel("年", "月", "", "", "", "")//默认设置为年月日时分秒
                .setType(new boolean[]{true, true, false, false, false, false})// 默认全部显示
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(17)//标题文字大小
                .isDialog(false)//是否显示为对话框样式
                .setTitleText("")//设置标题
                .setTitleSize(17)//设置标题字体大小
                .setTitleColor(Color.parseColor("#ff000000"))//设置标题字体颜色
                .setCancelColor(Color.parseColor("#ff000000"))//设置取消字体颜色
                .setSubmitColor(Color.parseColor("#018D47"))//设置确定字体颜色
                .setDividerColor(Color.parseColor("#E6E6E6"))//设置分割线的颜色
                .setTextColorCenter(Color.parseColor("#ff323232")) //设置选中项文字颜色
                .build();



        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                page = 1;
                String text = options1Items.get(options1).getPickerViewText();
                text_type_name.setText(text);
                deal_kind = options1Items.get(options1).getDeal_kind();
                InitData(0);
            }
        }).setTitleText("选择类型")//设置标题
                .setTitleSize(17)//设置标题字体大小
                .setTitleColor(Color.parseColor("#ff222222"))//设置标题字体颜色
                .setCancelColor(Color.parseColor("#ff000000"))//设置取消字体颜色
                .setSubmitColor(Color.parseColor("#018D47"))//设置确定字体颜色
                .setDividerColor(Color.parseColor("#E6E6E6"))//设置分割线的颜色
                .setTextColorCenter(Color.parseColor("#ff323232")) //设置选中项文字颜色
                .setContentTextSize(18)//设置内容文字的大小
                .build();


        SmartRefreshLayout swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                LoadData(1);
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                InitData(0);
                refreshLayout.finishRefresh();
            }
        });
    }

    private void InitData(int is_page_request) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(MyBillActivity.this));
        map.put("query_month", query_month);
        map.put("deal_kind", deal_kind);
        map.put("source", source);
        map.put("page", page);
        map.put("limit", 6);
        map.put("is_page_request", is_page_request);


        OkGo.<String>post(Constants.MY_BILL)
                .params("user_id", SPUtils.getAppUserId(MyBillActivity.this))
                .params("query_month", query_month)
                .params("deal_kind", deal_kind)
                .params("source", source)
                .params("page", page)
                .params("limit", 6)
                .params("is_page_request", is_page_request)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        MyBillBean myBillBean = gson.fromJson(response.body(), MyBillBean.class);

                        if (myBillBean.getCode() >= 0) {
                            tv_total_profit.setText(myBillBean.getResult().getCount_data().getTotal_profit()+"");
                            tv_user_balance.setText(myBillBean.getResult().getCount_data().getUser_balance()+"");
                            tv_total_withdraw_amount.setText(myBillBean.getResult().getCount_data().getTotal_withdraw_amount()+"");

                            //增加全部类型
                            options1Items.addAll(myBillBean.getResult().getDeal_kind_list());
                            pvOptions.setPicker(options1Items);//一级选择器

                            mybillAdapter.setNewData(myBillBean.getResult().getData_list());
                            View notDataView = getLayoutInflater().inflate(R.layout.item_empty_view, (ViewGroup) rv1.getParent(), false);
                            mybillAdapter.setEmptyView(notDataView);
                        } else {
                            Toast.makeText(MyBillActivity.this, myBillBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }




    private void LoadData(int is_page_request) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(MyBillActivity.this));
        map.put("query_month", query_month);
        map.put("deal_kind", deal_kind);
        map.put("source", source);
        map.put("page", page);
        map.put("limit", 6);
        map.put("is_page_request", is_page_request);


        OkGo.<String>post(Constants.MY_BILL)
                .params("user_id", SPUtils.getAppUserId(MyBillActivity.this))
                .params("query_month", query_month)
                .params("deal_kind", deal_kind)
                .params("source", source)
                .params("page", page)
                .params("limit", 6)
                .params("is_page_request", is_page_request)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        MyBillBean myBillBean = gson.fromJson(response.body(), MyBillBean.class);

                        if (myBillBean.getCode() >= 0) {
                            mybillAdapter.addData(myBillBean.getResult().getData_list());

                        } else {
                            Toast.makeText(MyBillActivity.this, myBillBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_close:
                finish();
                break;

            case R.id.linear_type://类型选择
                pvOptions.show();
                break;
            case R.id.linear_time://时间选择
                datepickview.show();
                break;

            default:
                break;
        }
    }


}
